import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/ui/user/profile.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/material.dart';

import '../../theme/theme_color.dart';
import '../../utils/default/Empty.dart';

class FansUi extends StatelessWidget {
  const FansUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _FansWidget();
  }
}

class _FansWidget extends StatefulWidget {
  const _FansWidget({Key? key}) : super(key: key);

  @override
  State<_FansWidget> createState() => _FansWidgetState();
}

class _FansWidgetState extends State<_FansWidget> {
  final _list = [];
  var _oneFansCount = 0; // 一度粉丝总数量
  var _twoFansCount = 0; // 二度粉丝总数量
  var _pageNum = 1;
  late ScrollController _scrollController;
  late GlobalKey<RefreshIndicatorState> _indicatorKey;

  @override
  void initState() {
    super.initState();
    _indicatorKey = GlobalKey<RefreshIndicatorState>();
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 20) {
        _pageNum++;
        _getFans();
      }
    });
    _indicatorKey.currentState?.show(atTop: true);
    _getFans();
  }

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      title: "我的粉丝",
      childWidget: Column(
        children: [
          Row(
            children: [
              Expanded(
                  child: Container(
                alignment: Alignment.center,
                height: 48,
                child: Text.rich(TextSpan(children: [
                  TextSpan(
                      text: "一度粉丝：",
                      style:
                          TextStyle(fontSize: 16, color: ThemeColor.textColor)),
                  TextSpan(
                      text: "$_oneFansCount人",
                      style:
                          TextStyle(fontSize: 16, color: ThemeColor.mainColor))
                ])),
              )),
              Expanded(
                  child: Container(
                alignment: Alignment.center,
                height: 48,
                child: Text.rich(TextSpan(children: [
                  TextSpan(
                      text: "二度粉丝：",
                      style:
                          TextStyle(fontSize: 16, color: ThemeColor.textColor)),
                  TextSpan(
                      text: "$_twoFansCount人",
                      style:
                          TextStyle(fontSize: 16, color: ThemeColor.mainColor))
                ])),
              ))
            ],
          ),
          Expanded(
            child: RefreshIndicator(
                key: _indicatorKey,
                onRefresh: _onRefresh,
                child: _list.isEmpty
                    ? const Empty()
                    : ListView.builder(
                        itemCount: _list.length,
                        controller: _scrollController,
                        physics: const AlwaysScrollableScrollPhysics(),
                        itemBuilder: (ctx, index) {
                          return _buildItem(index);
                        },
                      )),
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  Widget _buildItem(int index) {
    final itemData = _list[index];
    final itemWidget = GestureDetector(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (ctx) => UserProfileUi(memberId: itemData['id'])));
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(width: 1, color: ThemeColor.dividerColor))),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(24),
              child: Image.network(
                itemData['avatarImg'],
                width: 48,
                height: 48,
                fit: BoxFit.cover,
              ),
            ),
            const SizedBox(
              width: 12,
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  itemData['nickName'],
                  style: TextStyle(color: ThemeColor.textColor, fontSize: 15),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 8),
                  decoration: ShapeDecoration(
                      color: ThemeColor.mainColor,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12))),
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 3),
                  child: Text(
                    "${itemData['realSex'] == 1 ? '男' : '女'}    ${itemData['age'] == 0 ? '保密' : itemData['birthYear'].toString().split('-').first}",
                    style: TextStyle(
                        color: itemData['realSex'] == 1
                            ? Colors.blue
                            : ThemeColor.mainColor,
                        fontSize: 12),
                  ),
                )
              ],
            ),
            Expanded(
              child: Text.rich(
                TextSpan(style: const TextStyle(height: 1.5), children: [
                  TextSpan(
                      text: "二度粉丝\n",
                      style: TextStyle(color: ThemeColor.textColor)),
                  TextSpan(
                      text: "${itemData['fansCount']}人  ",
                      style: TextStyle(color: ThemeColor.mainColor))
                ]),
                textAlign: TextAlign.end,
              ),
            )
          ],
        ),
      ),
    );
    return itemWidget;
  }

  Future<void> _onRefresh() async {
    _pageNum = 1;
    _getFans();
  }

  _getFans() async {
    final _fansRes = await Api.getInstance().getFansList("", _pageNum, 20);
    dynamic _fansCount;
    if (_pageNum <= 1) {
      _fansCount = await Api.getInstance().getFansTotal();
    }
    final resList = [];
    if (_fansRes['code'] == 0) {
      final data = _fansRes['data'];
      if (data != null && data['list'] != null) {
        if (_pageNum <= 1) {
          _list.clear();
        }
        resList.addAll(data['list']);
      }
    } else {
      ThemeSnackBar.show(context, _fansRes['msg']);
    }
    var firCount = 0;
    var secCount = 0;
    if (_fansCount != null &&
        _fansCount['code'] == 0 &&
        _fansCount['data'] != null) {
      firCount = _fansCount['data']['oneFansCount'];
      secCount = _fansCount['data']['twoFansCount'];
    }
    setState(() {
      _list.addAll(resList);
      _oneFansCount = firCount;
      _twoFansCount = secCount;
    });
  }
}
